package ynu.elm.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import ynu.elm.entity.User;
import ynu.elm.mapper.IUserMapper;
import ynu.elm.service.UserService;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private IUserMapper userMapper;

    private final BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();

    @Override
    public User login(String username, String password) {
        try {
            // 根据用户名查询用户
            User user = userMapper.getUserByUsername(username);
            if (user != null && verifyPassword(password, user.getPassword())) {
                return user;
            }
        } catch (Exception e) {
            System.err.println("登录异常: " + e.getMessage());
        }
        return null;
    }

    @Override
    @Transactional
    public int register(String username, String password) {
        try {
            // 检查用户名是否已存在
            if (userMapper.countByUsername(username) > 0) {
                return 0;
            }

            // 创建新用户
            User newUser = new User();
            newUser.setUsername(username);
            newUser.setPassword(encodePassword(password));

            // 插入用户
            int result = userMapper.insertUser(newUser);
            return result > 0 ? 1 : -1;

        } catch (Exception e) {
            // 记录日志
            System.err.println("注册异常: " + e.getMessage());
            return -1;
        }
    }

    @Override
    public User getUserByUsername(String username) {
        try {
            return userMapper.getUserByUsername(username);
        } catch (Exception e) {
            System.err.println("查询用户异常: " + e.getMessage());
            return null;
        }
    }

    @Override
    public boolean verifyPassword(String rawPassword, String encodedPassword) {
        try {
            return passwordEncoder.matches(rawPassword, encodedPassword);
        } catch (Exception e) {
            System.err.println("密码验证异常: " + e.getMessage());
            return false;
        }
    }

    @Override
    //增强密码
    public String encodePassword(String rawPassword) {
        return passwordEncoder.encode(rawPassword);
    }
}